package com.qf.sms.controller;

import com.qf.dto.sms.SmsDTO;
import com.qf.result.R;
import com.qf.sms.exception.SmsSendException;
import com.qf.sms.service.SmsService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 处理短信的Controller
 * @version v1.0.0
 * @Description:
 * @author: 姜红凯
 * @date: 2022.04.10
 * @since 1.0
 */
@RestController
@RequestMapping("qf/sms")
public class SmsController {

    @Resource
    private SmsService smsService;

    /**
     * 发送短信的接口
     * @param smsDTO 发送短信的数据
     * @return 发送是否成功
     */
    @PostMapping("send")
    public R send(@RequestBody SmsDTO smsDTO){
        //1、接收其他子服务的参数
        String phoneNo = smsDTO.getPhoneNo();
        String code = smsDTO.getCode();
        Integer typeId = smsDTO.getTypeId();
        //2、发送短信，且保存历史
        try {
          int result=smsService.sendSms(phoneNo,code,typeId);
          if (result==0){
              //发送短信失败
              return R.error("发送短信失败");
          }else {
              //短信发送成功
              return R.ok("短信发送成功");
          }
        } catch (SmsSendException e) {
            //发送短信失败
            return R.error("发送短信失败");
        }

    }
    @PostMapping("check")
    public R check(@RequestBody SmsDTO smsDTO){
        String phoneNo=smsDTO.getPhoneNo();
        String code=smsDTO.getCode();
        Integer typeId=smsDTO.getTypeId();
        int result = smsService.checkSms(phoneNo, code, typeId);
        if(result==0){
            return R.ok(200,"短信验证成功");
        }else if(result==1) {
            return R.ok(501,"短信已经过期");
        }else{
            return R.ok(500,"短信验证错误");
        }
    }
}
